package com.toplabs.unashu.controller;


import cn.hutool.json.JSONObject;
import com.toplabs.unashu.common.response.CommonResponse;
import com.toplabs.unashu.common.response.ResponseStatus;
import com.toplabs.unashu.common.utils.JWTUtils;
import com.toplabs.unashu.dto.LoginDto;
import com.toplabs.unashu.entity.User;
import com.toplabs.unashu.exception.ServiceException;
import com.toplabs.unashu.service.LoginLogService;
import com.toplabs.unashu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ityanger
 * @since 2020-08-23
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    private final LoginLogService loginLogService;

    private final UserService userService;

    public UserController(UserService userService, LoginLogService loginLogService) {
        this.userService = userService;
        this.loginLogService = loginLogService;
    }

    @PostMapping("/login")
    public CommonResponse<JSONObject> login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        log.info("{}======{}", loginDto.getUsername(), loginDto.getPassword());
        @NotBlank(message = "用户名不为空")
        String username = loginDto.getUsername();
        @NotBlank(message = "密码不为空")
        String password = loginDto.getPassword();
        JSONObject jsonObject = userService.checkUser(username, password);
        loginLogService.saveLoginLog(request);
        return CommonResponse.success(jsonObject);
    }

    @GetMapping("/validate")
    public CommonResponse<JSONObject> validate(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        // 执行认证
        if (token == null) {
            throw new ServiceException(com.toplabs.unashu.common.response.ResponseStatus.NOT_TOKEN);
        }
        if (JWTUtils.isExpire(token)) {
            return CommonResponse.failed(com.toplabs.unashu.common.response.ResponseStatus.TOKEN_TIMEOUT);
        }
        String username = JWTUtils.getUsername(token);
        User user = userService.queryUserByName(username);
        if (user != null) {
            token = JWTUtils.sign(username, user.getPassword());
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("token", token);
            jsonObject.set("user", user);
            return CommonResponse.success(jsonObject);
        } else {
            return CommonResponse.failed(ResponseStatus.UNAUTHORIZED);
        }
    }
}
